package com.liuqianfei.markme.rules.inline;

import com.liuqianfei.markme.rules.AbstractState;
import com.liuqianfei.markme.rules.Delimiter;
import com.liuqianfei.markme.rules.IAction;

import java.util.List;

/**
 * For each opening emphasis-like marker find a matching closing one
 * @author liuqianfei
 */
public class BalancePairsAction implements IAction
{
    @Override
    public boolean parse(AbstractState state, boolean silent, int startLine, int endLine)
    {
        Delimiter lastDelim, currDelim;
        List<Delimiter> delimiters = state.getDelimiters();
        int max = state.getDelimiters().size();

        for (int i = 0; i < max; i++)
        {
            lastDelim = delimiters.get(i);

            if (!lastDelim.close)
                continue;

            int j = i - lastDelim.jump - 1;

            while (j >= 0)
            {
                currDelim = delimiters.get(j);

                if (currDelim.open &&
                        currDelim.marker == lastDelim.marker &&
                        currDelim.end < 0 &&
                        currDelim.level == lastDelim.level)
                {
                    // typeofs are for backward compatibility with plugins
                    boolean odd_match = (currDelim.close || lastDelim.open)
                            // FIXME ???
                            /*&& currDelim.length > 0 && lastDelim.length > 0*/
                            && (currDelim.length + lastDelim.length) % 3 == 0;

                    if (!odd_match)
                    {
                        lastDelim.jump = i - j;
                        lastDelim.open = false;
                        currDelim.end  = i;
                        currDelim.jump = 0;
                        break;
                    }
                }

                j -= currDelim.jump + 1;
            }
        }

        // FIXME I add it
        return true;
    }
}
